package com.cmhi.softmbh.util;

/**
 * Created by Administrator on 2017\10\26 0026.
 */

import android.text.TextUtils;
import android.widget.Toast;

import com.cmhi.softmbh.MyApplication;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Gson解析json的封装类
 * Created by Administrator on 2018/1/17.
 */
public class GsonUtils {

    private static final String TAG = GsonUtils.class.getSimpleName();


    public static <T> T jsonToBean(String json, Class<T> cls) {
       /* if (BuildConfig.DEBUG_SETTING) {
            return jsonToBeans(json, cls);
        }*/
        int index = -1;
        T t = null;
        if (!TextUtils.isEmpty(json)) {
            index = json.indexOf("{");
        }
        try {
            if (index == 0) {
                Gson gson = new Gson();
                t = gson.fromJson(json, cls);
                return t;
            } else if (index != -1) {
                json = "{\"stateCode\":\"0\",\"stateMsg\":\"服务器异常,请稍后重试\"}";
                Gson gson = new Gson();
                t = gson.fromJson(json, cls);
                return t;
            } else {
                Gson gson = new Gson();
                t = gson.fromJson(json, cls);
                return t;
            }
        } catch (Exception e) {
            if (cls != null) {
                try {
                    t = cls.newInstance();
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
            Toast.makeText(MyApplication.myApplication, "服务器异常,请稍后重试", Toast.LENGTH_SHORT).show();
        }
        return t;
    }

    public static <T> T jsonToBeans(String json, Class<T> cls) {
        Gson gson = new Gson();
        T t = gson.fromJson(json, cls);
        return t;
    }
    public static String toJson(Object src) {
        Gson gson = new Gson();
        return gson.toJson(src);
    }


    /**
     * 将对象转化为json
     *
     * @return
     */
    public static <T> String beanToJson(T t) {
        Gson g = new Gson();
        String str = "";
        if (t != null) {
            str = g.toJson(t);
        }
        return str;
    }

    //将list集合转化为字符串，这样使用在7.0及以上手机会出错
    private static <T> String listToJson1(List<T> list) {
        Gson gson = new Gson();
        Type type = new TypeToken<List<T>>() {
        }.getType(); // 指定集合对象属性
        String beanListToJson = gson.toJson(list, type);
        return beanListToJson;
    }

    public static <T> String listToJson(List<T> list) {
        StringBuilder beanListToJson = new StringBuilder();
        beanListToJson.append("[");
        int count = list.size();
        for (int i = 0; i < count; i++) {
            beanListToJson.append(beanToJson(list.get(i)));
            if (i != count - 1) {
                beanListToJson.append(",");
            } else {
                beanListToJson.append("]");
            }
        }
        return beanListToJson.toString();
    }


    /**
     * new TypeToken<List<T>>(){}.getType()运用到了java反射机制
     * 下面方法有问题，原因是泛型在编译期类型被擦除导致的，所以jsonToList()这个不能用，而使用fromJsonArray()方法
     * 解决方法：http://www.zhihu.com/question/27216298
     *
     * @param jsonString
     * @param cls
     * @return
     */
    private <T> List<T> jsonFromList(String jsonString, Class<T> cls) {
        List<T> list = null;
        try {
            Gson gson = new Gson();
            list = gson.fromJson(jsonString, new TypeToken<List<T>>() {
            }.getType());
        } catch (Exception e) {
        }
        return list;
    }

    /**
     * 成功解决了泛型在编译期类型被擦除导致的问题
     *
     * @param json
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> fromJsonList(String json, Class<T> clazz) {
        List<T> lst = new ArrayList<>();
        try {
            JsonArray array = new JsonParser().parse(json).getAsJsonArray();
            for (final JsonElement elem : array) {
                lst.add(new Gson().fromJson(elem, clazz));
            }
        } catch (Exception e) {
            Toast.makeText(MyApplication.myApplication, "服务器异常,请稍后重试", Toast.LENGTH_SHORT).show();
        }
        return lst;
    }

    /**
     * list转化成string
     *
     * @param list
     * @return
     */
    public static String listToString(List<String> list) {
        if (list == null) {
            return null;
        }
        StringBuilder result = new StringBuilder();
        boolean first = true;
        //第一个前面不拼接","
        for (String string : list) {
            if (first) {
                first = false;
            } else {
                result.append(",");
            }
            result.append(string);
        }
        return result.toString();
    }

    /**
     * string转换成list
     *
     * @param strs
     * @return
     */
    public static List<String> StringToList(String strs) {
        String str[] = strs.split(",");
        return Arrays.asList(str);
    }

}
